package com.mspbots.rule.exceptions.tsheet;

import com.mspbots.cw.request.SheetsTimeDTO;
import com.mspbots.rule.exceptions.BaseRule;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Fact;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Map;


@Slf4j
@Component
public abstract class TSheetBaseRule extends BaseRule implements ITSheetBaseRule {

    public TSheetBaseRule() {
    }


    protected boolean setTenantUserMapping(Long tsheetUserId, Long tenantId) {
        Map<String, Object> params = Map.of("sheetUserId", tsheetUserId, "tenantId", tenantId);
        this.tenantUserMappingDTO = this.tenantUserMappingService.findBySheetUser(params);
        return !ObjectUtils.isEmpty(tenantUserMappingDTO);
    }


    protected boolean checkMessage(SheetsTimeDTO tSheetsTimeDTO) {
//        messages.setTsheetTimesId(tSheetsTimeDTO.getId());
        return super.checkMessage(messages);
    }

    protected StringBuilder suffixSheetLink(Long sheetId) {
        StringBuilder messageBuilder = new StringBuilder();
        messageBuilder.append("[").append(sheetId).append("]&nbsp;");
        return messageBuilder;
    }

    protected StringBuilder suffixMessage(Long sheetId, LocalDateTime lastModified) {
        return new StringBuilder().append("--<span style='color:#999d9c;font-size:10px;'>")
                .append(suffixUserName())
//                .append(suffixSheetLink(sheetId))
                .append(suffixCwZoneTime(lastModified))
                .append("</span>");

    }

    protected String getMessage(SheetsTimeDTO tSheetsTimeDTO) {
        setTenantUserMapping(tSheetsTimeDTO.getTsUid(), tSheetsTimeDTO.getTenantId());
        if (tenantUserMappingDTO == null) {
            log.error("sheet_user_id not mapping teams user [{}]", tSheetsTimeDTO.getSheetUserId());
        }
        StringBuilder msg = formatMessage(true);
        msg.append(suffixMessage(tSheetsTimeDTO.getSheetId(), tSheetsTimeDTO.getLastModified()));
        return msg.toString();
    }

    protected boolean insertMessage() {
        messages.setBusinessType("tsheet_times");
        return super.insertMessage(messages);
    }


    @Action
    @Async
    @Override
    public void action(@Fact(FACT_TSHEET_TIMES) SheetsTimeDTO tSheetsTimeDTO) {
        messages.setMessage(getMessage(tSheetsTimeDTO));
        messages.setTsheetTimesId(tSheetsTimeDTO.getSheetId());
        messages.setBusinessId(tSheetsTimeDTO.getSheetId());
        insertMessage(messages);
    }

}
